package com.chen.project.white_jotter.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.project.white_jotter.mapper.BookMapper;
import com.chen.project.white_jotter.pojo.Book;
import com.chen.project.white_jotter.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class BookService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private RedisUtil redisUtil;

    // 查询一页图书
    public Map<String, Object> getPageBook(int pageNum, int pageSize, String query) {

        HashMap<String, Object> map = new HashMap<>();
        Page<Book> page = new Page<>(pageNum, pageSize);

        if(!"".equals(query)){
            QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("title", query);
            List<Book> bookList = bookMapper.selectPage(page, queryWrapper).getRecords();
            Integer count = bookMapper.selectCount(queryWrapper);
            map.put("bookList", bookList);
            map.put("count", count);
            return map;
        }

        if (redisUtil.get("book_list_page_" + pageNum) != null) {
            map = (HashMap<String, Object>) redisUtil.get("book_list_page_" + pageNum);
        } else {
            List<Book> bookList = bookMapper.selectPage(page, null).getRecords();
            Integer count = bookMapper.selectCount(null);
            map.put("bookList", bookList);
            map.put("count", count);
            redisUtil.set("book_list_page_" + pageNum, map);
            redisUtil.expire("book_list_page_" + pageNum, 20L, TimeUnit.MINUTES);
        }

        return map;
    }

    // 修改图书
    public int updateBook(Book book) {

        int i = bookMapper.updateByPrimaryKeySelective(book);

        Set<String> keys = redisUtil.keys("book_list_page_*");
        redisUtil.delete(keys);

        return i;
    }

    // 添加图书
    public int addBook(Book book) {
        int i = bookMapper.insertSelective(book);

        Set<String> keys = redisUtil.keys("book_list_page_*");
        redisUtil.delete(keys);

        return i;
    }

    // 删除图书
    public int deleteBookById(Integer id) {
        int i = bookMapper.deleteByPrimaryKey(id);

        Set<String> keys = redisUtil.keys("book_list_page_*");
        redisUtil.delete(keys);

        return i;
    }

    /**
     * es高亮搜索
     *
     * @param bookName
     * @return
     */
    public List<Book> search(String bookName) {

        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("title", bookName);
        List<Book> books = bookMapper.selectList(wrapper);
        return books;
    }
}
